using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing.Design;
using System.Drawing;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;

namespace SCS.Web.Controls.Design
{
	internal class MenuItemImageConverter : ExpandableObjectConverter
	{
		public override bool CanConvertFrom(ITypeDescriptorContext context, Type t)
		{
			if (t == typeof(string))
				return true;

			return base.CanConvertFrom(context, t);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) 
		{
			if (destType == typeof(InstanceDescriptor) || destType == typeof(string)) 
			{
				return true;
			}
			return base.CanConvertTo(context, destType);
		}	
		
		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo info, object value)
		{
			if (value is string)
			{
				string str = (string)value;
					
				try
				{
					string[] properties = str.Replace(" ", "").Split(',');
					
					int height = -1;
					string[] nameValue = properties[0].Split('=');
					
					if (nameValue.Length > 0)
						height = int.Parse(nameValue[1]);

					int width = -1;
					nameValue = properties[1].Split('=');

					if (nameValue.Length > 0)
						width = int.Parse(nameValue[1]);

					return new MenuItemImage(height, width, properties[0]);
				}
				catch
				{
					return new MenuItemImage();
				}				
			}
			return base.ConvertFrom(context,info,value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo info, object value, Type destType )
		{
			if (destType == typeof(string))
			{
				MenuItemImage image = (MenuItemImage)value;
				
				string text = string.Empty;

				if (image.Url.Length > 0)
				{
					text = string.Format("{0}, Height={1}, Width={2}", image.Url, image.Height, image.Width); 	
				}
				
				return text;
			}
			else if (destType == typeof(InstanceDescriptor)) 
			{
				Type[] types = new Type[] { typeof(int), typeof(int), typeof(string) };
				ConstructorInfo constructorInfo = typeof(MenuItemImage).GetConstructor(types);
				
				MenuItemImage image = (MenuItemImage)value;
				object[] args = new object[] { image.Height, image.Width, image.Url };

				InstanceDescriptor descriptor = new InstanceDescriptor(constructorInfo, args, true);

				return descriptor;
			}
			return base.ConvertTo(context, info, value, destType);
		}
	}
}



